package com.czk.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

import javax.net.ssl.SSLException;
import java.io.File;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/5/8 10:31
 */
public class NettyClient {
    public static void main(String[] args) throws SSLException {
        new NettyClient().connect("localhost", 7397);
    }

    private void connect(String host, int port) throws SSLException {
        // 引入SSL安全验证
        File certChainFile = new File("F:\\IdeaProjects\\netty\\netty-ssl\\src\\main\\java\\com\\czk\\ssl\\server\\server.crt");
        File keyFile = new File("F:\\IdeaProjects\\netty\\netty-ssl\\src\\main\\java\\com\\czk\\ssl\\server\\pkcs8_server.key");
        File rootFile = new File("F:\\IdeaProjects\\netty\\netty-ssl\\src\\main\\java\\com\\czk\\ssl\\server\\ca.crt");
        SslContext sslContext = SslContextBuilder.forServer(certChainFile, keyFile).trustManager(rootFile).clientAuth(ClientAuth.REQUIRE).build();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.AUTO_READ, true)
                    .handler(new MyClientInitializer(sslContext));
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            System.out.println("客户端启动成功");
            channelFuture.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
        }
    }
}
